package Main;

import java.awt.Graphics;
import World.*;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;

import Constructions.Construction;
import FrameWork.Menu;
import Menus.*;
import Power.PowerNode;

public class MenuManager 
{
	int bestLevel = 1; // Should only be used for the function that closes menus because it doesn't account level 0.
	boolean retainsCursor = false, hasFullMenu = false;
	public ArrayList<Menu> menuList = new ArrayList<Menu>();
	SpaceGame main;
	
	public MenuManager(SpaceGame main)
	{
		
		this.main = main;
		menuList.add(new AnnouncementMenu(main));
		menuList.add(new SideMenu(main));
		menuList.add(new ResourceMenu(main));
	}
	
	public void draw(Graphics g)
	{
		for(Menu m:menuList)
		{
			m.draw(g);
		}
	}
	
	public void addMenu(Menu m)
	{
		menuList.add(m);
		if (m.getLevel() > bestLevel)
			bestLevel = m.getLevel();
		if (m.requiresCursor())
			main.cursor.setActive(true);
		String name = m.getClass().getSimpleName();
		if (name.charAt(0) == 'F' && name.charAt(1) == 'u' && name.charAt(2) == 'l' && name.charAt(3) == 'l')
		{
			main.setPaused(true);
			hasFullMenu = true;
		}
	}
	
	public void removeMenu(Menu m)
	{
		menuList.remove(m);
	}
	
	public void closeLevel()
	{
		World.showingPower = false;
		for(Construction c:main.constructionManager.constructionList)
		{
			c.setFlashing(false);
		}
		for(PowerNode p:main.powerManager.nodeList)
		{
			p.setFlashing(false);
		}
		retainsCursor = false;
		bestLevel = 1;
		for(Menu m:menuList)
		{
			if (m.getLevel()>=bestLevel)
			{
				bestLevel = m.getLevel();
			}
		}
		try
		{
			for(Menu m:menuList)
			{
				if (m.getLevel() >= bestLevel)
				{
					removeMenu(m);		//Still has concurrent modification exception but it is hidden.
				}
				if (m.getLevel() > bestLevel)
				{
					System.out.println("Level out of bounds Error");
				}
			}
		}
		catch (ConcurrentModificationException e) 
		{
			
		}
		bestLevel--;
		for(Menu m:menuList)
		{
			if (m.getLevel() == bestLevel && m.requiresCursor())
			{
				retainsCursor = true;
			}
		}
		if (retainsCursor)
			main.cursor.setActive(true);
		else
			main.cursor.setActive(false);
		if (bestLevel == 0)
		{
			hasFullMenu = false;
		}
	}
	
	public int getTopLevel()
	{
		int topLevel = 0;
		for(Menu m:menuList)
		{
			if (m.getLevel() > topLevel)
				topLevel = m.getLevel();
		}
		return topLevel;
	}
	
	public ArrayList<Menu> getTopMenus()
	{
		ArrayList<Menu> topMenus = new ArrayList<Menu>();
		int topLevel = getTopLevel();
		for (Menu m:menuList)
		{
			if (m.getLevel() == topLevel)
				topMenus.add(m);
		}
		return topMenus;
	}
	
	public boolean hasFullMenu()
	{
		return hasFullMenu;
	}
	
	public void setHasFullMenu(boolean a)
	{
		this.hasFullMenu = a;
	}
}
